package com.weita.lightfood.service;

import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaTemplateData;
import cn.binarywang.wx.miniapp.bean.WxMaTemplateMessage;
import cn.binarywang.wx.miniapp.config.WxMaInMemoryConfig;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * description:
 *  消息推送
 * @author IT_Monster on 2019/8/21
 */
@Service
public class PushService {

    @Value("${wechat.appId}")
    private String appId;
    @Value("${wechat.appSecret}")
    private String appSecret;
    @Value("${wechat.pushToUserTemplateId}")
    private String pushToUserTemplateId;

    /**
     * 微信小程序消息推送给用户，提醒用户订单正在配送中
     * @param openId    用户openid
     * @param formId    表单id
     * @param templateDataList 消息模板
     * @return
     */
    public String wechatPushToUser(String openId, String formId, List<WxMaTemplateData> templateDataList){
        //配置小程序信息
        WxMaInMemoryConfig wxConfig = new WxMaInMemoryConfig();
        //设置appId
        wxConfig.setAppid(appId);
        wxConfig.setSecret(appSecret);
        System.out.println("appid="+appId);
        System.out.println("appSecret="+appSecret);

        WxMaServiceImpl wxService = new WxMaServiceImpl();
        wxService.setWxMaConfig(wxConfig);

        WxMaTemplateMessage templateMessage = WxMaTemplateMessage.builder()
                .toUser(openId)
                .formId(formId)
                .templateId(pushToUserTemplateId)
                .data(templateDataList)
                .page("")
                .build();

        try {
            wxService.getMsgService().sendTemplateMsg(templateMessage);
        } catch ( WxErrorException e ) {
            System.out.println("推送失败");
            e.printStackTrace();
            return "error";
        }
        return "success";
    }

    public String wechatPush(String openId, String formId){
        //设置消息模板
        List<WxMaTemplateData> templateDataList = new ArrayList<>();
        WxMaTemplateData data1 = new WxMaTemplateData("keyword1","神秘物品");
        WxMaTemplateData data2 = new WxMaTemplateData("keyword2","123456789");
        WxMaTemplateData data3 = new WxMaTemplateData("keyword3","60元");
        WxMaTemplateData data4 = new WxMaTemplateData("keyword4","2019-08-18");
        templateDataList.add(data1);
        templateDataList.add(data2);
        templateDataList.add(data3);
        templateDataList.add(data4);
        return wechatPushToUser(openId, formId, templateDataList);
    }
}
